﻿using AgvDispatchSystemWpf.DAL;
using ZwxCommunication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.IO.Ports;
using AgvDispatchSystemWpf.Model;
using System.Data;
using System.Windows;

namespace AgvDispatchSystemWpf.BLL
{
    public class DispatchSystemBll
    {
        DataAcess da = new DataAcess();

        public DataResult<SerialInfo> InitialSerialInfo()
        {
            DataResult<SerialInfo> result = new DataResult<SerialInfo>();

            try
            {
                SerialInfo si = new SerialInfo
                {
                    PortName = ConfigurationManager.AppSettings["port"].ToString(),
                    BaudRate = int.Parse(ConfigurationManager.AppSettings["baud"].ToString()),
                    DataBit = int.Parse(ConfigurationManager.AppSettings["data_bit"].ToString()),
                    Parity = (Parity)Enum.Parse(typeof(Parity), ConfigurationManager.AppSettings["parity"].ToString()),
                    StopBits = (StopBits)Enum.Parse(typeof(StopBits), ConfigurationManager.AppSettings["stop_bit"].ToString(), true)
                };

                result.State = true;
                result.Data = si;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }

        public DataResult<List<DeviceModel>> InitialDevices()
        {
            DataResult<List<DeviceModel>> result = new DataResult<List<DeviceModel>>();
            try
            {
                var devices = da.GetDevices();
                var monitorValues = da.GetMonitorValues();

                List<DeviceModel> deviceList = new List<DeviceModel>();

                foreach (var dr in devices.AsEnumerable())
                {//遍历设备列表
                    DeviceModel dModel = new DeviceModel() {
                        DeviceId = dr.Field<string>("d_id"),
                        DeviceName = dr.Field<string>("d_name"),
                        IsRunning = true,
                        IsWarning=false
                    };
                    deviceList.Add(dModel);
                    foreach (var mv in monitorValues.AsEnumerable().Where(m=>m.Field<string>("d_id")==dModel.DeviceId))
                    {//遍历与该设备id相同的监控变量
                        MonitorValueModel mvm = new MonitorValueModel() {
                            ValueId = mv.Field<string>("value_id"),
                            ValueName = mv.Field<string>("value_name"),
                            Address = mv.Field<string>("address"),
                            DataType = mv.Field<string>("data_type"),
                            IsAlarm = mv.Field<Int32>("is_alarm") == 1,
                            ValueDesc=mv.Field<string>("description"),
                            Unit=mv.Field<string>("unit"),
                          
                        };

                        // 警戒值
                        var column = mv.Field<string>("alarm_lolo");
                        mvm.LoLoAlarm = column == null ? 0.0 : double.Parse(column);
                        column = mv.Field<string>("alarm_low");
                        mvm.LowAlarm = column == null ? 0.0 : double.Parse(column);
                        column = mv.Field<string>("alarm_high");
                        mvm.HighAlarm = column == null ? 0.0 : double.Parse(column);
                        column = mv.Field<string>("alarm_hihi");
                        mvm.HiHiAlarm = column == null ? 0.0 : double.Parse(column);

                        dModel.MonitorValueList.Add(mvm);

                        mvm.ValueStateChanged = (state, msg, value_id) =>
                        {
                            try
                            {
                                Application.Current?.Dispatcher.Invoke(() =>
                                {
                                    var index = dModel.WarningMessageList.ToList().FindIndex(w => w.ValueId == value_id);
                                    if (index > -1)
                                        dModel.WarningMessageList.RemoveAt(index);//实时报警集合中是否有该变量，如果有的话先删除

                                    if (state != Base.MonitorValueState.OK)//如果变量报警
                                    {//将该变量加入到设备的实时报警集合中
                                        dModel.IsWarning = true;
                                        dModel.WarningMessageList.Add(new WarningMessageModel { ValueId = value_id, Message = msg });
                                    }
                                });

                                var ss = dModel.WarningMessageList.Count > 0;//存在报警为真
                                if (dModel.IsWarning != ss)
                                {
                                    dModel.IsWarning = ss;
                                }
                            }
                            catch { }
                        };
                    }
                }
                result.State = true;
                result.Data = deviceList;
            }
            catch (Exception ex)
            {
                result.Message = ex.ToString();
            }
            return result;
        }
    }
}
